package com.whj.wkpt.controller;

import com.whj.wkpt.dto.PageResultDTO;
import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskApplication;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.TaskApplicationService;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/freelancer")
public class FreelancerController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskApplicationService taskApplicationService;

    @Autowired
    private UserService userService;

    // 浏览所有可申请的任务（支持分页和条件查询）
    /**
     * 显示可申请任务列表，支持分页和条件查询
     * 
     * @param title 任务标题查询条件（可选）
     * @param taskStatus 任务状态查询条件（可选）
     * @param page 当前页码，默认为0
     * @param size 每页显示记录数，默认为6
     * @param model 视图模型
     * @return 任务列表页面
     */
    @GetMapping("/tasks")
    public String listAvailableTasks(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String taskStatus,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "6") int size,
            Model model) {
        // 使用分页查询方法
        PageResultDTO<Task> pageResult = taskService.findTasksWithPagination(title, taskStatus, page, size);
        model.addAttribute("tasks", pageResult.getContent());
        model.addAttribute("currentPage", pageResult.getPage());
        model.addAttribute("totalPages", pageResult.getTotalPages());
        model.addAttribute("totalElements", pageResult.getTotalElements());
        model.addAttribute("title", title);
        model.addAttribute("taskStatus", taskStatus);
        return "freelancer/task-list";
    }

    // 查看任务详情
    @GetMapping("/tasks/{taskId}")
    public String viewTask(@PathVariable Long taskId, Model model, Authentication authentication) {
        Task task = taskService.findById(taskId);
        model.addAttribute("task", task);
        
        // 检查是否已申请该任务
        boolean alreadyApplied = false;
        boolean taskTaken = false;
        
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        if (currentUser != null) {
            List<TaskApplication> applications = taskApplicationService.findByTaskId(taskId);
            taskTaken = !applications.isEmpty();
            
            for (TaskApplication app : applications) {
                if (app.getFreelancerId().equals(currentUser.getUserId())) {
                    alreadyApplied = true;
                    break;
                }
            }
        }
        
        model.addAttribute("alreadyApplied", alreadyApplied);
        model.addAttribute("taskTaken", taskTaken);
        
        return "freelancer/task-detail";
    }

    // 申请任务
    @PostMapping("/tasks/{taskId}/apply")
    public String applyForTask(@PathVariable Long taskId, Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        if (currentUser != null) {
            // 检查任务是否已经被承接
            List<TaskApplication> existingApplications = taskApplicationService.findByTaskId(taskId);
            if (existingApplications.isEmpty()) {
                // 创建任务申请
                TaskApplication application = new TaskApplication();
                application.setTaskId(taskId);
                application.setFreelancerId(currentUser.getUserId());
                application.setDeliveryStatus("not_delivered");
                taskApplicationService.createApplication(application);
                
                // 更新任务状态为进行中
                Task task = taskService.findById(taskId);
                if (task != null && "open".equals(task.getTaskStatus())) {
                    task.setTaskStatus("in_progress");
                    taskService.updateTask(task);
                }
            }
        }
        
        // 修改跳转地址到"查看我的申请"页面
        return "redirect:/freelancer/my-applications";
    }

    // 标记任务为已交付
    @PostMapping("/applications/{applicationId}/deliver")
    public String deliverTask(@PathVariable Long applicationId, Authentication authentication) {
        // 重定向到任务应用详情页面进行交付
        return "redirect:/freelancer/task-applications/" + applicationId + "/submit-delivery";
    }

    // 查看我申请的任务
    @GetMapping("/my-applications")
    public String listMyApplications(Authentication authentication, Model model) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);
        
        List<TaskApplication> applications = null;
        Map<Long, Task> taskMap = new HashMap<>();
        if (currentUser != null) {
            applications = taskApplicationService.findByFreelancerId(currentUser.getUserId());
            
            // 为每个申请获取对应的任务信息
            for (TaskApplication app : applications) {
                Task task = taskService.findById(app.getTaskId());
                taskMap.put(app.getApplicationId(), task);
            }
        }
        
        model.addAttribute("applications", applications);
        model.addAttribute("taskMap", taskMap);
        return "freelancer/my-applications";
    }
}